package logobj.utils;

import java.io.*;

public class BinaryFileUtils {
    /**
     * 读取二进制文件
     * */
    public static  byte[] readByteFromText(String filename){
        byte[] textbytearr = null;
        BufferedInputStream bufferedInputStream = null;
        try {
            bufferedInputStream = new BufferedInputStream(new FileInputStream(filename));
            int len = bufferedInputStream.available();
            textbytearr = new byte[len];
            bufferedInputStream.read(textbytearr,0,len);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != bufferedInputStream){
                try {
                    bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return textbytearr;
    }

    /***
     * 将字节数组写入文本文件
     * */
    public static void writeByteToText(String filename , byte[] barr){
        FileOutputStream fileOutputStream = null;
        try {
            File binfile = new File(filename);
            if(binfile.exists()){
                binfile.delete();
            }
            binfile.createNewFile();
            fileOutputStream = new FileOutputStream(filename);
            fileOutputStream.write(barr);
            //fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(fileOutputStream != null){
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
